package cn.xutongxue.gtms.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.xutongxue.gtms.entity.File;
import cn.xutongxue.gtms.service.FileUploadService;
import cn.xutongxue.gtms.utils.OSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {

    @Resource
    private OSSUtil ossUtil;
    @Resource
    private UserServiceImpl userService;
    @Resource
    private FileServiceImpl fileService;
    @Value("${upload.saveToLocal}")
    private boolean saveToLocal;
    @Value("${upload.localPath}")
    private String localPath;

    @Override
    public File uploadFile(MultipartFile file) {
        File uploadFile = new File();
        InputStream inputStream = null;
        uploadFile.setFilename(file.getOriginalFilename());
        uploadFile.setStore(saveToLocal ? "0" : "1");
        if (saveToLocal) {
            try {
                inputStream = file.getInputStream();
                String target = DateUtil.format(DateUtil.date(), "yyyyMMdd") + "/"
                        + IdUtil.simpleUUID() + "." + FileUtil.extName(file.getOriginalFilename());
                // 本地保存路径
                String fullPath = localPath + "/" + target;
                // 复制文件
                Files.copy(inputStream, Paths.get(fullPath), StandardCopyOption.REPLACE_EXISTING);
                // 设置文件路径等信息
                uploadFile.setPath(target);
                uploadFile.setUploader(StpUtil.getLoginIdAsLong());
                fileService.save(uploadFile);
                IoUtil.close(inputStream);
                return uploadFile;
            } catch (Exception e) {
                log.warn(e.getMessage());
                throw new RuntimeException("File upload failed.", e);
            } finally {
                // 确保输入流被关闭
                IoUtil.close(inputStream);
            }
        } else {
            // 待修改完善 ossUtil
            // ossUtil.uploadFile(file);
            return uploadFile;
        }
    }

    @Override
    public Boolean removeFile(Long fileId) {
        File file = fileService.getById(fileId);
        if (saveToLocal) {
            try {
                FileUtil.del(localPath + "/" + file.getPath());
                return true;
            } catch (Exception e) {
                log.warn(e.getMessage());
            }
        } else {
            return false;
            // ossUtil.deleteFile(file.getPath());
        }
        return false;
    }

    @Override
    @Transactional
    public File uploadAvatar(MultipartFile file) {
        File uploadFile = new File();
        InputStream inputStream = null;
        uploadFile.setFilename(file.getOriginalFilename());
        uploadFile.setStore(saveToLocal ? "0" : "1");
        if (saveToLocal) {
            try {
                inputStream = file.getInputStream();
                String target = DateUtil.format(DateUtil.date(), "yyyyMMdd") + "/avatar/"
                        + IdUtil.simpleUUID() + "." + FileUtil.extName(file.getOriginalFilename());
                // 本地保存路径
                String fullPath = localPath + "/"  + target;
                // 确保目录存在
                Files.createDirectories(Paths.get(fullPath).getParent());
                // 复制文件
                Files.copy(inputStream, Paths.get(fullPath), StandardCopyOption.REPLACE_EXISTING);
                // 设置文件路径等信息
                uploadFile.setPath(target);
                uploadFile.setUploader(StpUtil.getLoginIdAsLong());
                uploadFile.setType("头像");
                fileService.save(uploadFile);
                IoUtil.close(inputStream);
                return uploadFile;
            } catch (Exception e) {
                log.warn(e.getMessage());
                throw new RuntimeException("File upload failed.", e);
            } finally {
                // 确保输入流被关闭
                IoUtil.close(inputStream);
            }
        } else {
            // 待修改完善 ossUtil
            // ossUtil.uploadFile(file);
            return uploadFile;
        }
    }
}